var Data = require('./data.js');
var io = require('./io.js');

var Catch = Data.catch;
var db = Data.data;

var len = 0;

function Chat(socket) {
    Catch.number++;

    var request = socket.request;
    socket.roomName = request.headers.origin;
    if ('rn' in request._query) {
        socket.roomName += request._query.rn;
    }

    //get info
    socket.info = {};
    socket.info.id = '-' + (++len);
    if ('name' in request._query) {
        socket.info.name = request._query.name;
    } else {
        socket.info.name = '游客:' + socket.info.id;
    }
    if ('avatar' in request._query) {
        socket.info.avatar = request._query.avatar;
    } else {
        socket.info.avatar = 'http://oss.imconfig.com/cn/imconfig/0.0.0/img/avatar/1%20%28' + Math.floor(Math.random() * 70 + 1) + '%29.jpg';
    }

    //join
    socket.join(socket.roomName);
    if (socket.roomName in Catch) {
        Catch[socket.roomName]++;
    } else {
        Catch[socket.roomName] = 1;
    }

    socket.lastTime = Date.now() - db.speed;
    socket.on('chat', function(msg, callback) {
        var time = Date.now();
        if (time - this.lastTime < db.speed) {
            callback('error');
            return;
        }
        this.lastTime = time;

        if (msg.text === '') {
            callback('error');
            return;
        }
        this.in(this.roomName).emit('chat', {
            total: Catch.number,
            number: Catch[this.roomName]
        }, this.info, msg);
        callback({
            total: Catch.number,
            number: Catch[this.roomName]
        }, this.info, msg);
    });

    socket.on('disconnect', function() {
        socket.leave(socket.roomName);
        Catch[socket.roomName]--;
        Catch.number--;
    });

    socket.emit('in', {
        speed: db.speed,
        info: socket.info,
        total: Catch.number,
        number: Catch[socket.roomName]
    });
};

module.exports = Chat;